
export function GetServerTimeSeconds (): number {
  // 创建一个新的 Date 对象，表示当前时间
  const now = new Date()
  // getTime() 方法返回从 1970 年 1 月 1 日 00:00:00 UTC 到当前时间的毫秒数
  // 将毫秒数除以 1000 得到秒数，并使用 Math.floor 向下取整
  return Math.floor(now.getTime() / 1000)
}

export function GetServerTimezoneOffsetSeconds (): number {
  // 获取本地时间与 UTC 时间的时差，单位为秒
  const offset = new Date().getTimezoneOffset() * 60
  return offset
}

export function GetDayIndexBySeconds (seconds: number): number {
  return Math.floor(seconds / (24 * 60 * 60))
}

// return [0, val)
export function ServerRandomInt (val: number): number {
  return Math.floor(val * Math.random())
}

// return [min, max]
export function ServerRandomBetween (min: number, max: number): number {
  // 确保 min 小于等于 max
  if (min > max) {
    [min, max] = [max, min]
  }

  const val = Math.floor((max - min + 1) * Math.random())
  return val + min
}

export function ServerRandomWithWeights<T extends ({[k:string]: number & any})> (targets:T[], weightKey: string): T {
  if (targets.length == 1)
    return targets[0]
  let totalWeight = 0
  for (const t of targets) {
    totalWeight += t[weightKey]
  }
  if (totalWeight <= 0) {
    console.warn('ServerRandomWithWeights total weight = 0', new Error().stack)
    return targets[targets.length - 1]
  }
  let val = ServerRandomBetween(1, totalWeight)
  for (const t of targets) {
    val -= t[weightKey]
    if (val <= 0)
      return t
  }

  console.warn(`ServerRandomWithWeights random value left = ${val}`, new Error().stack)
  return targets[targets.length - 1]
}